package com.other.server;


import com.other.util.CloseUtil;

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.util.Date;

public class Response {
    private Socket client;
    private BufferedWriter bw;

    private StringBuilder headInfo = new StringBuilder();
    private StringBuilder content= new StringBuilder();

    public static final String CRLF="\r\n";
    public static final String BLANK=" ";
    Response(Socket client){
        this.client = client;
    }
    Response(OutputStream os){
        this.bw = new BufferedWriter(new OutputStreamWriter(os));
    }
    public void println(StringBuilder info) {
        content.append(info).append(CRLF);
    }

    private void creatHead(int code){
        //heard
        headInfo.append("").append("HTTP/1.1")
                .append(BLANK).append(code).append(BLANK);
        switch(code){
            case 200:
                headInfo.append("OK");
                break;
            case 404:
                headInfo.append("NOT FOUND");
                break;
            case 505:
                headInfo.append("SEVER ERROR");
                break;
        }
        headInfo.append(CRLF);

        //2)  响应头(Response Head)
        headInfo.append("Server:bjsxt Server/0.0.1").append(CRLF);
        headInfo.append("Date:").append(new Date()).append(CRLF);
        headInfo.append("Content-type:text/html;charset=UTF-8").append(CRLF);
        //正文长度 ：字节长度
        headInfo.append("Content-Length:").append(content.toString().getBytes().length).append(CRLF);
        headInfo.append(CRLF); //分隔符
    }

    public void push(int code) throws IOException {
        creatHead(code);
        bw.append(headInfo.toString());
        bw.append(content.toString());
        bw.flush();
        close();

    }
    private void close(){
        CloseUtil.closeIO(bw);
    }


}
